/**
 * Created by chenxuebin on 2017/3/10.
 */
function handlerData(res) {
    return res.records;
}

function stateFormatter(value, row, index) {
    if (value == 1)
        return "启用";
    else if (value == -1)
        return "禁用";
    else return "未知";
}

function sfFormatter(value, row, index) {
    return value == 1 ? "是" : "否";
}

function typeFormatter(value, row, index) {
    console.log(">>>typeFormatter")
    console.log(row)
    return value;
    if (value == 1)
        return "启用";
    else
        return "禁用";
}

function imgFormatter(value, row, index) {
    if (value) {
        return "<img src='" + value + "' width='25' height='25'>"
    } else {
        return "未上传图标";
    }
}

function tsFormatter(value, row, index) {

    if (!value) return "-"
    var date = new Date(value+"000");

}

function actionFormatter(value, row, index) {
    var state = row.state;
    var id = row.id;
    var res = '<button data-toggle="modal" class="btn-sm btn-primary" href="list.html#modal-form" data-row=' + id + ' data-index=' + index + '>修改</button>';
    if (state == undefined) {
    } else if (state == 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',-1)" >禁用</button>';
    else
        res += ' <button typ-e="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',1)" >启用</button>';
    res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="deleteOne(\'' + id + '\')">删除</button>';
    return res;
}

function xftypeFormatter(value, row, index) {
    //* 消费类型@1：充值；2：提现；3：赚佣金；4：消费；5：赠送金额；6：扣款；8:退款；9:卖货；11：交押金；12：退押金
    if (value == undefined || value == "") return "";
    else if (value == 1)
        return "充值";
    else if (value == 2)
        return "提现";
    else if (value == 3)
        return "赚佣金";
    else if (value == 4)
        return "消费";
    else if (value == 5)
        return "赠送金额";
    else if (value == 6)
        return "扣款";
    else if (value == 8)
        return "退款";
    else if (value == 9)
        return "卖货";
    else if (value == 11)
        return "交押金";
    else if (value == 12)
        return "退押金";
    else return ""
}

var dateformat = {
    autoclose: true,
    clearBtn: false, //清除按钮
    todayBtn: false, //今日按钮
    format: "yyyy-mm-dd"
};

function closeModal() {
    $('#modal-form').modal('hide');
}

/*
 * 切换Switchery开关函数
 * * switchElement Switchery对象
 * * checkedBool 选中的状态
 */
function setSwitchery(switchElement, checkedBool) {
    if ((checkedBool && !switchElement.isChecked()) || (!checkedBool && switchElement.isChecked())) {
        switchElement.setPosition(true);
        switchElement.handleOnchange(true);
    }
}

function getPreviewList(photos) {
    var preList = new Array();
    if (!photos || photos.length == 0) return preList;

    photos = photos.split(";");
    for (var i = 0; i < photos.length; i++) {
        if (photos[i].length == 0) continue
        // var array_element = photos[i];
        // 此处指针对.txt判断，其余自行添加
        // if (array_element.fileIdFile.name.indexOf("txt") > 0) {
        //     // 非图片类型的展示
        //     preList[i] = "<div class='file-preview-other-frame'><div class='file-preview-other'><span class='file-icon-4x'><i class='fa fa-file-text-o text-info'></i></span></div></div>"
        // } else {
        // 图片类型
        // preList[i] = "<img src='" + photos[i] + "' class='file-preview-image'/>";
        // }
        preList.push(photos[i])
    }
    return preList;
}

function getPreviewConfig(photos, ptype, feild, id) {
    var conList = new Array();
    if (!photos || photos.length == 0) return conList;

    photos = photos.split(";");
    for (var i = 0; i < photos.length; i++) {
        if (photos[i].length == 0) continue
        // var array_element = photos[i];
        // 此处指针对.txt判断，其余自行添加
        // if (array_element.fileIdFile.name.indexOf("txt") > 0) {
        //     // 非图片类型的展示
        //     preList[i] = "<div class='file-preview-other-frame'><div class='file-preview-other'><span class='file-icon-4x'><i class='fa fa-file-text-o text-info'></i></span></div></div>"
        // } else {
        // 图片类型
        // preList[i] = "<img src='" + photos[i] + "' class='file-preview-image'/>";
        // }
        var filename = photos[i].substr(photos[i].lastIndexOf("/") + 1);
        var cf = {
            caption: filename,
            size: 827000,
            width: "200px",
            url: "/admin/rm/file?ptype=" + ptype + "&feild=" + feild + "&id=" + id,
            key: i
        }
        conList.push(cf)
    }
    return conList;
}

function filedeleted(photos, key) {
    var parr = [], ps = [];
    if (!photos || photos.length == 0) return "";

    ps = photos.split(";");
    console.log("========================photos")
    console.log("========================key=" + key)
    console.log(photos)
    for (var i = 0; i < ps.length; i++) {
        if (ps[i] == "") continue;
        if (i != key) parr.push(ps[i])
    }
    var result = parr.join(";");
    // if (result.indexOf(";") == 0) result = result.substring(1, result.length - 1)
    return parr.length == 0 ? "" : result;
}

function filedeletedbak(photos, photosvak, key) {
    var parr = [], ps = [];
    if (!photos || photos.length == 0) return "";
    if (!photosvak || photosvak.length == 0) return "";

    ps = photosvak.split(";");
    console.log("========================photos")
    console.log("========================key=" + key)
    console.log(photos)
    console.log(photosvak)
    photos = photos.replace(ps[key], '').replace(';;', ';')
    return photos.length == 1 ? "" : photos;
}

function uploadFile(file, editor, welEditable, type) {
    var mfile = new FormData();
    mfile.append("mfile", file);
    $.ajax({
        url: '/admin/upload/file?type=' + (type || 'ungroup'), // 图片上传url
        type: 'POST',
        data: mfile,
        cache: false,
        contentType: false,
        processData: false,
        dataType: 'json', // 以json的形式接收返回的数据
        // 图片上传成功
        success: function (r) {
            console.log(r)
            console.log(">>>editor=" + editor)
            swal({title: "上传成功", text: "", type: "success"})
            if (type == "image") {
                // var imgNode = document.createElement("img");
                // imgNode.src = $result.img;
                // editor.summernote('insertNode', imgNode);
                // editor.summernote('insertImage', data.response.data);
                // $("#"+editor).summernote('editor.insertImage', data.response.data);
                // $("#"+editor+" .note-editable").append(r.data);
                // $("#"+editor+" .note-editable").append(r.data);
                editor.insertImage(welEditable, r.data);
            } else {
            }
        },
        // 图片上传失败
        error: function () {
            swal({title: "上传失败", text: "", type: "error"})
        }
    });
}

// 表单自动校验
jQuery.validator.addMethod("phone", function (value, element) {
    var length = value.length;
    var reg = /^(13[0-9]{9})|(14[0-9]{9})|(15[0-9]{9})|(16[0-9]{9})|(17[0-9]{9})|(18[0-9]{9})|(19[0-9]{9})$/;
    return this.optional(element) || (length == 11 && reg.test(value));
}, "请输入正确的手机号码");

jQuery.validator.addMethod("idcard", function (value, element) {
    var length = value.length;
    var reg = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/;
    return this.optional(element) || reg.test(value);
}, "请输入正确的身份证号码");

jQuery.validator.addMethod("url", function (value, element) {
    var length = value.length;
    var reg = /^((https?|ftp|http):\/\/)?([a-z]([a-z0-9\-]*[\.。])+([a-z]{2}|aero|arpa|biz|com|cn|coop|edu|gov|info|int|jobs|mil|museum|name|nato|net|org|pro|travel)|(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(:[0-9]{1,4})?)(\/[a-z0-9_\-\.~]+)*(\/([a-z0-9_\-\.]*)(\?[a-z0-9+_\-\.%=&]*)?)?(#[a-z][a-z0-9_]*)?$/;
    return this.optional(element) || reg.test(value);
}, "请输入正确的网址");

jQuery.validator.addMethod("lzero", function (value, element) {
    var length = value.length;
    var reg = /^-[1-9]\d*$/;//负整数
    return this.optional(element) || reg.test(value);
}, "请输入负整数格式");

jQuery.validator.addMethod("gzero", function (value, element) {
    var length = value.length;
    var reg = /^[1-9]\d*$/;// 正整数
    return this.optional(element) || reg.test(value);
}, "请输入正整数格式");

jQuery.validator.addMethod("num", function (value, element) {
    var length = value.length;
    var reg = /^[0-9]\d*$/;// 整数
    return this.optional(element) || reg.test(value);
}, "请输入整数");

jQuery.validator.addMethod("money", function (value, element) {
    var length = value.length;
    var reg = /^[0-9]+(.[0-9]{2})?$/;// 校验金额
    return this.optional(element) || reg.test(value);
}, "请输入正确金额");

jQuery.validator.addMethod("zn", function (value, element) {
    var length = value.length;
    var reg = /^[\u4e00-\u9fa5]{0,}$/;// 校验中文
    return this.optional(element) || reg.test(value);
}, "请输入正确的中文信息");

jQuery.validator.addMethod("zn", function (value, element) {
    var length = value.length;
    var reg = /^[A-Za-z]+$/;// 校验英文
    return this.optional(element) || reg.test(value);
}, "请输入正确的英文信息");

jQuery.validator.addMethod("carno", function (value, element) {
    var length = value.length;
    var reg = /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z_0-9]{5}$/;// 车牌号
    return this.optional(element) || reg.test(value);
}, "请输入正确的车牌号信息");

// 全局校验
jQuery.extend({
    num: function (v, showTip) {
        if (!(/^-?\d+$/.test(v))) {
            if (showTip) alert("输入整数格式有误，请重填");
            return false;
        } else {
            return true;
        }
    }
})

function delimg(el, idxx) {
    var hel = '#hid' + el
    var imgs = $(hel).val().split(";");
    console.log('------------------------delimg')
    console.log('-------el=' + el)
    console.log('-------idxx=' + idxx)
    $(hel).val('')

    $("#sort" + el).empty()
    for (var i = 0; i < imgs.length; i++) {
        var idx = el + i
        if (imgs[i] == idxx) continue;
        $("#sort" + el).append('<div id="' + idx + '" src="' + imgs[i] + '" style="position: relative;width:100px;height:100px;display: inline"><img src="' + imgs[i] + '"   /><img src="/img/del.png" onclick="delimg(\'' + el + '\',\'' + imgs[i] + '\')" style="width:20px;height:20px;position: absolute;right: 0;top:-50px;cursor:pointer"/></div>')
        $(hel).val($(hel).val().length == 0 ? imgs[i] : $(hel).val() + ";" + imgs[i]);
    }

    Sortable.create(document.getElementById('sort' + el), {
        animation: 150,
        store: null,
        onAdd: function (evt) {
            console.log('-----------onAdd.foo:', [evt.item, evt.from]);
        },
        onUpdate: function (evt) {
            console.log('-----------onUpdate.foo:', [evt.item, evt.from]);
        },
        onRemove: function (evt) {
            console.log('-----------onRemove.foo:', [evt.item, evt.from]);
        },
        onStart: function (evt) {
            console.log('-----------onStart.foo:', [evt.item, evt.from]);
        },
        onSort: function (evt) {
            console.log('-----------onSort.foo:', [evt.item, evt.from]);
            console.log(evt)
            $(hel).val('')
            $("#sort" + el).children().each(function (i, item) {
                $(hel).val($(hel).val().length == 0 ? $(item).attr("src") : $(hel).val() + ";" + $(item).attr("src"));
            })
            console.log($(hel).val())
        },
        onEnd: function (evt) {
            console.log('-----------onEnd.foo:', [evt.item, evt.from]);
        }
    });

    console.log($(hel).val())
}

function createsort(el) {
    console.log('----------------come createsort')
    var hel = '#hid' + el
    var imgs = $(hel).val().split(";");
    console.log(imgs)
    $("#sort" + el).empty()
    for (var i = 0; i < imgs.length; i++) {
        var idx = el + i
        $("#sort" + el).append('<div id="' + idx + '" src="' + imgs[i] + '" style="position: relative;width:100px;height:100px;display: inline"><img src="' + imgs[i] + '"   /><img src="/img/del.png" onclick="delimg(\'' + el + '\',\'' + imgs[i] + '\')" style="width:20px;height:20px;position: absolute;right: 0;top:-50px;cursor:pointer"/></div>')
    }

    return Sortable.create(document.getElementById('sort' + el), {
        animation: 150,
        store: null,
        onAdd: function (evt) {
            console.log('-----------onAdd.foo:', [evt.item, evt.from]);
        },
        onUpdate: function (evt) {
            console.log('-----------onUpdate.foo:', [evt.item, evt.from]);
        },
        onRemove: function (evt) {
            console.log('-----------onRemove.foo:', [evt.item, evt.from]);
        },
        onStart: function (evt) {
            console.log('-----------onStart.foo:', [evt.item, evt.from]);
        },
        onSort: function (evt) {
            console.log('-----------onSort.foo:', [evt.item, evt.from]);
            console.log(evt)
            $(hel).val('')
            $("#sort" + el).children().each(function (i, item) {
                $(hel).val($(hel).val().length == 0 ? $(item).attr("src") : $(hel).val() + ";" + $(item).attr("src"));
            })
            console.log($(hel).val())
        },
        onEnd: function (evt) {
            console.log('-----------onEnd.foo:', [evt.item, evt.from]);
        }
    });
}

